import {Injectable, OnModuleInit} from "@nestjs/common";
import {InjectRepository} from "@nestjs/typeorm";
import {SysMenu} from "../entity/SysMenu";
import {Repository} from "typeorm";
import config from "../config";
import {Result} from "../common/Result";
import {INIT_CONSTANTS} from "../InitProjectConstant";
import {SysRole} from "../entity/SysRole";
import {JwtConstant} from "../common/constant/JwtConstant";

/**
 * 菜单service
 */
@Injectable()
export class SysMenuService implements OnModuleInit{
    @InjectRepository(SysMenu)
    private menuRepository: Repository<SysMenu>;

    @InjectRepository(SysRole)
    private roleRepository: Repository<SysRole>

    /**
     * 初始化
     */
    onModuleInit() {
        if (!config.doInit) {
            return;
        }
        let data = INIT_CONSTANTS.menus;
        let list: SysMenu[] = [];
        let id = 0;
        for (let i = 0; i < data.length; i++) {
            for (let j = 0; j < data[i].length; j++) {
                data[i][j].menuId = (id = id + 1);
                data[i][j].parentId = j == 0 ? null : data[i][0].menuId;
                data[i][j].orderNum = j;

                let temp = <SysMenu>data[i][j];
                temp.icon = "el-icon-menu";
                // @ts-ignore
                temp.parent = j == 0 ? null : data[i][0];
                list.push(temp);
            }
        }
        // await this.menuRepository.query(`drop table if exists sys_menu_closure`).then(res => {});
        this.menuRepository.save(list).then(res => {
            console.log("初始化菜单成功...");
        })
        // console.log("初始化菜单....", list);

    }

    /**
     * 添加菜单
     * @param menu
     */
    async addMenu(menu: SysMenu) {
        menu.parentId = menu.parent?.menuId;
        try {
            await this.menuRepository.save(menu);
        } catch (e) {
            return Result.failed();
        }
        return Result.success();
    }

    /**
     * 菜单列表
     * @param sysMenu
     */
    async menuList(sysMenu?: SysMenu) {
        return await this.menuRepository.manager.getTreeRepository(SysMenu).findTrees();
    }

    /**
     * 获取用户菜单
     */
    async getUserNav() {
        let role = JwtConstant.getUserRole();
        let sysRole = await this.roleRepository.findOne({where: {roleId: role}, relations: ["menus"]});
        let { menus } = sysRole;
        menus = SysMenu.toTree(menus);
        return Result.success("获取用户菜单", menus);
    }
}
